import { login, getUserInfo, getUserDetailByid } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
const state = {
  token: getToken(),
  userInfo: {}
}

const mutations = {
  setToken(state, payload) {
    // 保存到vuex
    state.token = payload
    // 保存到本地
    setToken(payload)
  },
  setUserInfo(state, payload) {
    state.userInfo = payload
  },
  // 删除token
  removeToken() {
    state.token = null
    removeToken()
  },
  // 清空用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  },
  // 退出
  logout() {
    this.commit('user/removeToken')
    this.commit('user/removeUserInfo')
  }
}

const actions = {
  // 登录请求
  async login(context, data) {
    const res = await login(data)
    context.commit('setToken', res)
  },
  // 获取用户资料
  async getUserInfo(context) {
    // 获取用户基本信息里的id
    const userInfo = await getUserInfo()
    // 通过id获取详细信息
    const userDetail = await getUserDetailByid(userInfo.userId)
    context.commit('setUserInfo', {
      ...userInfo,
      ...userDetail
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
